package com.atguigu.paymentdemo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.atguigu.paymentdemo.config.AlipayClientConfig;
import com.atguigu.paymentdemo.entity.OrderInfo;
import com.atguigu.paymentdemo.enums.OrderStatus;
import com.atguigu.paymentdemo.enums.PayType;
import com.atguigu.paymentdemo.mapper.OrderInfoMapper;
import com.atguigu.paymentdemo.mapper.ProductMapper;
import com.atguigu.paymentdemo.service.AliPayService;
import com.atguigu.paymentdemo.service.OrderInfoService;
import com.atguigu.paymentdemo.service.PaymentInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author longge
 * @Title:
 * @Description:
 * @date 2023/2/13 22:39
 */
@Service
@Slf4j
public class AliPayServiceImpl implements AliPayService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private AlipayClientConfig alipayClientConfig;

    @Autowired
    private PaymentInfoService paymentInfoService;

    private final ReentrantLock lock = new ReentrantLock();

    /**
     * @Description: 统一下单
     * @param productId
     * @return
     */
    @Override
    @Transactional
    public String tradeCreate(Long productId) {
        try {
            //生成订单
            OrderInfo orderInfo = orderInfoService.createOrderByProductId(productId, PayType.ALIPAY.getType());

            //调用支付宝接口
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setNotifyUrl(alipayClientConfig.getNotifyUrl());
            request.setReturnUrl(alipayClientConfig.getReturnUrl());

            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderInfo.getOrderNo());
            BigDecimal totalFee = new BigDecimal(orderInfo.getTotalFee().toString()).divide(new BigDecimal("100"));
            bizContent.put("total_amount", totalFee);
            bizContent.put("subject", orderInfo.getTitle());
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
            request.setBizContent(bizContent.toString());

            //调用支付宝接口
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            if(response.isSuccess()){
                log.info("调用成功,返回结果为 ===》{}",response.getBody());
            } else {
                log.info("调用失败,返回结果为 ===》{}",response.getBody());
                throw new RuntimeException("创建交易失败");
            }
            return  response.getBody();
        } catch (AlipayApiException e) {
            log.info("调用支付宝统一下单接口异常");
            e.printStackTrace();
            throw new RuntimeException("创建交易失败");
        }
    }

    /**
     * @Description: 处理订单
     * @param params
     */
    @Override
    public void processOrder(Map<String, String> params) {

        String orderNo = params.get("out_trade_no");

        if(lock.tryLock()){
            try {
                //接口调用的幂等性
                String status = orderInfoService.getOrderStatus(orderNo);
                if (!OrderStatus.NOTPAY.getType().equals(status)) {
                    return;
                }

                //更新订单状态
                orderInfoService.updateStausByOrderNo(orderNo, OrderStatus.SUCCESS);

                //记录支付日志
                paymentInfoService.createPaymentInfoForALi(params);
            } finally {
                lock.unlock();
            }
        }
    }
}
